package cn.crex1.xiaomi.core.orm.mapper;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.crex1.xiaomi.core.orm.datasource.Configuration;
import cn.crex1.xiaomi.core.orm.datasource.JdbcDataSource;

public class MapperProxy implements InvocationHandler {
	private  Map<Method, MapperMethod> methodCache=new ConcurrentHashMap<>();
	private JdbcDataSource dataSource;
	private Class<?> clazz;
	private Object[] args;

	public MapperProxy(JdbcDataSource dataSource, Class<?> clazz, Object[] args) {
		this.dataSource = dataSource;
		this.clazz = clazz;
		this.args = args;
		
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		if (Object.class.equals(method.getDeclaringClass())) {
			method.invoke(this, args);
		}
		MapperMethod MapperMethod = cachedMapperMethod(method);
		String methodname=MapperMethod.getMethodName();
		String sql=MapperMethod.getSqlvaluecache();
		String result=MapperMethod.getResultcache();
		String methdresult=MapperMethod.getMethodResultcache();
		List<Object> argsList=MapperMethod.getArgscache();
		Configuration configuration=new Configuration(args,dataSource, sql,result, argsList,methdresult);
		return configuration.excute();
	}
	private MapperMethod cachedMapperMethod(Method method) {
	    MapperMethod mapperMethod = methodCache.get(method);
	    if (mapperMethod == null) {
	      mapperMethod = new MapperMethod();
	      mapperMethod.registryMapper(clazz,method, args);
	      methodCache.put(method, mapperMethod);
	    }
	    return mapperMethod;
	  }
}
